/**
 * 加载api接口配置文件
 * by @author lms 2022.07.18
 */
package ms.core.gateway.tool;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import ms.core.gateway.dto.Api;
import ms.core.tool.Log4j2Tool;
import ms.core.tool.StrTool;

public class ApiLoadTool {
	/**
	 * 加载api配置
	 * 
	 * @param type api类型(0-系统;1-应用;2-授权公开)
	 * @param fileName api配置文件名称
	 * @return
	 */
	public static Map<String, Api> loadApi(int type, String fileName){
		Map<String, Api> ret = new HashMap<>();
        try {
            InputStream in = ApiLoadTool.class.getResourceAsStream(fileName);
            SAXReader reader = new SAXReader();
            Document doc = reader.read(in);
            Element root = doc.getRootElement();
            List<Element> items = root.elements();
            for (Element fun : items) {
                Api api = new Api();

                api.setType(type);
                api.setApiName(fun.attributeValue("apiName"));
                api.setClassName(fun.attributeValue("className"));
                api.setClientId(fun.attributeValue("clientId"));
                api.setFunction(fun.attributeValue("function"));
                api.setAcl(fun.attributeValue("acl"));
                api.setRate(StrTool.strToFloat(fun.attributeValue("rate"), 0));
                api.setLogEvent("true".equalsIgnoreCase(fun.attributeValue("logEvent")));
                api.setLogParam("true".equalsIgnoreCase(fun.attributeValue("logParam")));
                api.setFileFilter(fun.attributeValue("fileFilter"));
                api.setFileSize(StrTool.strToLong(fun.attributeValue("fileSize"), 0));
                api.setFileNum(StrTool.strToInt(fun.attributeValue("fileNum"), 0));
                api.setDescription(fun.attributeValue("desc"));

                ret.put(api.getApiName(), api);
            }
            in.close();
        } catch (Exception e) {
            Log4j2Tool.error(ApiLoadTool.class, "parserXml:"+fileName, e);
        }
        return ret;
    }
}
